package com.base.myproject.client.HR.setting;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseTreeStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseGridPanel;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Button;

/**
 * @author cxghiu4102@gmail.com
 * 班次设定
 *
 */
public class WorkBatchSet extends BaseJDBCPanel {
	String tree_depcode = null;// 讲当前树形结构中选中的部门id保存
	String tree_de_name = null;// 讲当前树形结构中选中的部门name保存
	TreePanel<TreeNodeModelData> treePanel = null;
	BaseStore<BusiObject> store = null;	
	public WorkBatchSet() {
		init();
	}
	
	public void init() {
		initTreePanel();
		initWeigetx();
		registerMainStore(store);
	}

	public void complete() {
		super.complete();
	}
	
	public void initWeigetx() {
		BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST,
				200);
		westData.setCollapsible(true);
		westData.setFloatable(true);
		westData.setHideCollapseTool(true);
		westData.setSplit(true);
		westData.setMargins(new Margins(5, 5, 0, 2));

		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 2, 0, 0));
		
		BorderLayout layout = new BorderLayout();
		ContentPanel panel = new ContentPanel();  
		panel.setLayout(layout);
		Tools.setResize(panel, 1.0, 1.00);
		panel.setHeaderVisible(false);
		
		ContentPanel west = new ContentPanel();  
		ContentPanel center = new ContentPanel(); 
		
		west.add(getTreePanel());
		west.setHeading("选择部门");
		west.setCollapsible(true);
		
		center.add(getBaseGrid());
		//center.setHeight(500);
		center.setHeaderVisible(false);
		panel.setBodyBorder(false);

		panel.add(west, westData);
		panel.add(center, centerData);
		
		add(panel);
	}
	
	BaseTreeStore<TreeNodeModelData> treeStore = null;
	
	TreePanel<TreeNodeModelData> getTreePanel() {
		if (treePanel == null) {
			initTreePanel();
		}
		return treePanel;
	}

	BaseTreeStore<TreeNodeModelData> getTreeStore() {
		if (treeStore == null) {
			initTreeStore();
		}
		return treeStore;
	}

	// 创建班次数据连接
	BaseTreeStore<TreeNodeModelData> initTreeStore() {
		StoreInfo si = new StoreInfo();
		si
				.setSql("select icode,id,name from SystemInfo where id is not null order by id asc");
		si.setTreesortcolumn("id");
		si.setKeyname(new String[] { "icode" });
		si.setTablename("SystemInfo");
		treeStore = new BaseTreeStore<TreeNodeModelData>(si, false);
		treeStore.load();
		return treeStore;

	}
	
	void initTreePanel() {
		treePanel = new TreePanel<TreeNodeModelData>(getTreeStore());
		treePanel.setWidth(200);
		treePanel.setHeight(445);
		treePanel.setBorders(false);
		treePanel.setDisplayProperty("name");
		treePanel.setCheckStyle(CheckCascade.PARENTS);
		treePanel.setCheckNodes(CheckNodes.BOTH);
		treePanel.getStyle().setLeafIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.tree_file())); 
		treePanel.setCheckable(false);
		treePanel.setAutoLoad(true);

		treePanel.addListener(Events.OnClick,
				new Listener<TreePanelEvent<TreeNodeModelData>>() {
					public void handleEvent(TreePanelEvent<TreeNodeModelData> be) {
						if(be.getItem() == null) return;
						String id = be.getItem().get("id").toString();
						tree_depcode = id;
						tree_de_name = be.getItem().get("name").toString();
						set_grid(id);
					}
				});

	}
	
	BaseStore<BusiObject> getStore() {// String bcode
		if (store == null) {
			createStore();// bcode
		}
		return store;
	}

	void createStore() {// String bcode
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");

		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("depCode");
		type.getField("depCode").setType(String.class);
		type.addField("depName");
		type.getField("depName").setType(String.class);

		type.addField("batchName");
		type.getField("batchName").setType(String.class);
		type.addField("batchNo");
		type.getField("batchNo").setType(String.class);

		type.addField("bgnTime1");
		type.getField("bgnTime1").setType(String.class);
		type.addField("endTime1");
		type.getField("endTime1").setType(String.class);
		type.addField("Span1");
		type.getField("Span1").setType(String.class);

		type.addField("bgnTime2");
		type.getField("bgnTime2").setType(String.class);
		type.addField("endTime2");
		type.getField("endTime2").setType(String.class);
		type.addField("Span2");
		type.getField("Span2").setType(String.class);
		
		type.addField("calculation_length");
		type.getField("calculation_length").setType(Double.class);
		type.addField("working_hours");
		type.getField("working_hours").setType(Double.class);
		

		StoreInfo info = new StoreInfo();
		info.setTablename("hr_Attendance_WorkBatch");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from hr_Attendance_WorkBatch where depCode is not null");
		info.setForcenolimit("true");

		store = new BaseStore<BusiObject>(type, info);
	}
	
	BaseStore<BusiObject> mainStore() {
		BaseStore<BusiObject> mainStore = null;
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");

		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("id");
		type.getField("id").setType(String.class);
		type.addField("name");
		type.getField("name").setType(String.class);

		StoreInfo si = new StoreInfo();
		si.setTablename("SystemInfo");
		si.setKeyname(new String[] { "icode" });
		si.setSql("select * from SystemInfo");

		mainStore = new BaseStore<BusiObject>(type, si);
		return mainStore;
	}
	
	void set_grid(String id) {
		StoreInfo info2 = new StoreInfo();
		info2.setTablename("hr_Attendance_WorkBatch");
		info2.setKeyname(new String[] { "icode" });
		String where = " where 1=1 and ";
		if (id.length() < 5) {
			where = where + " depCode like '" + id + "%25'";
		} else {
			where = where + " depCode = '" + id + "'";
		}

		grid.getBg().getStore().getStoreinfo().setSql("select * from hr_Attendance_WorkBatch " + where);
		grid.getBg().getStore().reload();
	}
	
	BaseGridPanel grid = null;
	TextField<String> df1 = new TextField<String>();
	TextField<String> df2 = new TextField<String>();
	TextField<String> df3 = new TextField<String>();
	TextField<String> df4 = new TextField<String>();
	// 部门名称
	TextField<String> tf1 = new TextField<String>();
	
	TextField<String> tf2 = new TextField<String>();// 班次代码
	
	TextField<String> tf3 = new TextField<String>();// 班次名称

	Button seach_bt = new Button("查询");
	NumberField nf = new NumberField();

	BaseComboBoxForm<BaseModelData> bc3 = new BaseComboBoxForm<BaseModelData>(
			"id", "name", "systeminfo", "", true);

	BaseGridPanel getBaseGrid() {
		if (grid == null) {
			createGrid();
		}
		return grid;
	}

	void createGrid() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig C2 = new ColumnConfig("depCode", "部门", 80);
		bc3.setReadOnly(true);
		C2.setRenderer(bc3);
		C2.setEditor(bc3.getCelEditor());
		columns.add(C2);

		ColumnConfig C1 = new ColumnConfig("batchName", "班次名称", 80);
		C1.setEditor(new CellEditor(tf3));
		columns.add(C1);

		ColumnConfig C3 = new ColumnConfig("batchNo", "班次代码", 60);
		tf2.setName("batchNo");
		C3.setEditor(new CellEditor(tf2));
		columns.add(C3);

		ColumnConfig C4 = new ColumnConfig("bgnTime1", "起始时间1", 80);
		//df1.addListener(Events.Change, getListener());
		C4.setEditor(new CellEditor(df1));
		columns.add(C4);

		ColumnConfig C5 = new ColumnConfig("endTime1", "结束时间1", 80);
		//df2.addListener(Events.Change, getListener());
		C5.setEditor(new CellEditor(df2));
		columns.add(C5);

		ColumnConfig C8 = new ColumnConfig("Span1", "是否跨天1", 80);
		columns.add(C8);

		ColumnConfig C6 = new ColumnConfig("bgnTime2", "起始时间2", 80);
		//df3.addListener(Events.Change, getListener());
		C6.setEditor(new CellEditor(df3));
		columns.add(C6);

		ColumnConfig C7 = new ColumnConfig("endTime2", "结束时间2", 80);
		//df4.addListener(Events.Change, getListener());
		C7.setEditor(new CellEditor(df4));
		columns.add(C7);

		ColumnConfig C9 = new ColumnConfig("Span2", "是否跨天2", 80);
		columns.add(C9);
		
		ColumnConfig C10 = new ColumnConfig("calculation_length", "计算时长", 80);
		columns.add(C10);
		ColumnConfig C11 = new ColumnConfig("working_hours", "工作时长", 80);
		nf.setPropertyEditorType(Double.class);
		C11.setEditor(new CellEditor(nf));
		nf.addListener(Events.Change, getListener());
		columns.add(C11);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGridPanel(getStore(), cm, true, true) {
			@SuppressWarnings("unchecked")
			public void addnewrecord() {
				if (tree_depcode == null) {
					MessageBox.alert("警告", "请选择一个部门后再添加新信息", null);
					return;
				}
				HashMap hp = new HashMap();
				hp.put("depCode", tree_depcode);
				hp.put("depName", tree_de_name);
				hp.put("batchNo", "");
				hp.put("bgnTime1", "");
				hp.put("endTime1", "");
				hp.put("bgnTime2", "");
				hp.put("endTime2", "");
				hp.put("Span1", "否");
				hp.put("Span2", "否");

				grid.getBg().getStore().add(hp);
			}
		};
		grid.getBg().addListener(Events.OnClick, getListener());// 单击grid的时候
																// ，想进行数据修改的时候
		grid.getBg().addListener(Events.AfterEdit, getListener());														
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid.setTitle("班次信息");
		grid.getBg().setSelectionModel(cbs);
		grid.getBg().setBorders(false);
		Tools.setResize(grid.getBg(), 0.95, 0.94);
	}
	
	int sync = 0;
	Listener<BaseEvent> defaultlistener;
	private int index = -100;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}
		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.OnClick) {
							if (be.getSource().equals(grid)) {
								if (tree_depcode == null) {
									MessageBox.alert("警告", "请先选择一个部门 再操作！",
											null);
									return;
								}
							}
						} else if (be.getType() == Events.Change) {
							/******************* 判断时间的事件 ******************/
							double d = Double.parseDouble(store.getValue("calculation_length").toString());
							if (d < Double.parseDouble(nf.getRawValue())) {
								MessageBox.alert("提示", "工作时长不能大于计算时长，请重新输入工作时长，谢谢", null);
								nf.setRawValue("0");
								return;
							}
						} else if (be.getType() == Events.AfterEdit) {
							GridEvent<BusiObject> ge = (GridEvent) be;// 开始
							index = ge.getRowIndex();
							String bgnTime1 = (String)grid.getBg().getValue(index, "bgnTime1");
							String endTime1 = (String)grid.getBg().getValue(index, "endTime1");
							String bgnTime2 = (String)grid.getBg().getValue(index, "bgnTime2");
							String endTime2 = (String)grid.getBg().getValue(index, "endTime2");
							
							if (ge.getProperty().equals("batchNo")) {// 可同时监听多个字段ge.getProperty().equals("amount")
								check_bc(tf2, index);
							}else if(ge.getProperty().equals("bgnTime1")){
								if (!checkTime(df1)) {
									MessageBox.alert("警告",
											"输入的'开始时间1'不合法！请重新输入", null);
								} else {
									updateDuration(bgnTime1, endTime1, bgnTime2, endTime2);
								}
							}else if(ge.getProperty().equals("endTime1")){
								if (!checkTime(df2)) {
									MessageBox.alert("警告",
											"输入的'结束时间1'不合法！请重新输入", null);
								} else {
									updateDuration(bgnTime1, endTime1, bgnTime2, endTime2);
								}
							}else if(ge.getProperty().equals("bgnTime2")){
								if (!checkTime(df3)) {
									MessageBox.alert("警告", "输入的起始时间2不合法！请重新输入",null);
								}else {
									updateDuration(bgnTime1, endTime1, bgnTime2, endTime2);
								}
							}else if(ge.getProperty().equals("endTime2")){
								if (!checkTime(df4)) {
									MessageBox.alert("警告", "输入的结束时间2不合法！请重新输入",
											null);
								} else {
									updateDuration(bgnTime1, endTime1, bgnTime2, endTime2);
								}
							}
							
						}else if (be.getType() == Events.KeyUp) {

							if (be instanceof ComponentEvent) {
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{
								}
							}
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}
	
	private void updateDuration(String t1, String t2, String t3, String t4) {
		Double time1 = 0d;
		Double time2 = 0d;
		
		if	(t1 != null && t2 != null && !t1.equals("") && !t2.equals("")){
			String[] t1Array = t1.split(":");
			String[] t2Array = t2.split(":");
			if (checkSize(t1Array, t2Array)) {
				grid.getBg().setValue(index, "Span1", "否");
				time1 =get_work_length(t1Array,t2Array,0);
			} else {
				grid.getBg().setValue(index, "Span1", "是");
				time1 =get_work_length(t1Array,t2Array,1);
			}
		}
		
		if (t1 == null || t2 == null) {
			grid.getBg().setValue(index, "Span1", "否");
		}
		
		if (t3 == null || t4 == null) {
			grid.getBg().setValue(index, "Span2", "否");
		}
		
		if	(t3 != null && t4 != null && !t3.equals("") && !t4.equals("")){
			String[] t3Array =t3.split(":"); 
			String[] t4Array = t4.split(":");
			if (checkSize(t3Array, t4Array)) {
				grid.getBg().setValue(index, "Span2", "否");
				time2 = get_work_length(t3Array,t4Array,0);
			} else {
				grid.getBg().setValue(index, "Span2", "是");
				time2 = get_work_length(t3Array,t4Array,1);
			}
		}
		
		grid.getBg().setValue(index, "calculation_length",time1 + time2);
		grid.getBg().setValue(index, "working_hours", time1 + time2);
	}
	
	//TextField<String> TextField_temp = new TextField<String>();// grid中的text公共变量
	void check_bc(final TextField<String> te,final int index){
		final String Bno = te.getValue().toUpperCase().replaceAll(" ", "");
		// 判断当前输入的班次号码是否在班次表中存在
		String sql = "SELECT count(*) as c FROM hr_Attendance_WorkBatch WHERE (depCode LIKE '"
				+ tree_depcode
				+ "%' or depCode='00') AND batchNo='"
				+ Bno
				+ "' ";
		//TextField_temp = te;
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService.getDataSet(sql, new AsyncCallback<DataSet>() {
			@Override
			public void onFailure(Throwable caught) {
			}
			@Override
			public void onSuccess(DataSet result) {
				if (result.getValue(0, "c").equals("0")) {// 返回结果为0
					grid.getBg().setValue(index, te.getName(), Bno);
				} else {
					Info.display("", "输入的班次代码已存在,请重新输入！");
					grid.getBg().setValue(index, te.getName(), "");
					
				}
			}
		});
	}
	
	/*
	 * 验证时间
	 */
	
	boolean checkTime(TextField<String> tf) {
		String bt1 = tf.getValue();
		if (bt1 == null) {
			return true;
		}
		char[] ch = bt1.toCharArray();
		if (ch.length != 5) {
			return false;
		}
		int num1 = ch[0];
		int num2 = ch[1];
		int num3 = ch[2];
		int num4 = ch[3];
		int num5 = ch[4];
		if (num1 > 51 || num1 < 47 || num2 < 47 || num3 > 58 || num3 != 58
				|| num4 < 47 || num4 > 54 || num5 < 47 || num5 > 58) {
			return false;
		}
		return true;
	}
	
	/*
	 * 验证开始时间与结束时间的大小
	 */
	boolean checkSize(String[] t1, String[] t2) {
		if(t1[0].equals("24")){t1[0]="00";}
		if(t2[0].equals("24")){t2[0]="00";}
		//false ="是跨天" true='否'
		if (Integer.parseInt(t1[0]) > Integer.parseInt(t2[0])) {
			return false;
		}else if (Integer.parseInt(t1[0]) == Integer.parseInt(t2[0])) {
			if (Integer.parseInt(t1[1]) >= Integer.parseInt(t2[1])) {
				return false;
			}
		}
		return true;
	}
	Double get_work_length(String[] t1, String[] t2,int t){//t=1:跨天，0：不跨天 ；没有跨天的情况
		//if(t1[0].equals("00")){t1[0]="24";}
		//if(t2[0].equals("00")){t2[0]="24";}
		Double w_length=0.00;
		if(t==0){
			Double hour=Double.valueOf(t2[0])-Double.valueOf(t1[0]);//得到小时差 h
			Double min=(Double.valueOf(t2[1])-Double.valueOf(t1[1]))/60;//得到分钟差 m
			w_length=hour+min;
		}else{
			Double hour1=24.00-(Double.valueOf(t1[0])+(Double.valueOf(t1[1])/60));//得到前一天小时差 h
			Double hour2=Double.valueOf(t2[0])+(Double.valueOf(t2[1])/60);//得到后一天小时差 h
			w_length=hour1+hour2;
		}
		
		
		
		w_length=(double)Math.round(w_length*100)/100;
		return w_length;
	}
	
	
	public void setCheckNodes(CheckNodes checkNodes) {
		treePanel.setCheckNodes(checkNodes);
	}
	
	protected void save() {
		if (index == -100) {
			store.trySave();
		} else {
			// r1的列下标为4
			index = -100;//还原成任何保存状态
			String text_value = "";
			text_value = tf2.getValue().toUpperCase().replaceAll(" ", "");// check_p(tC6,index);
			String sql = "SELECT batchNo FROM hr_Attendance_WorkBatch WHERE (depCode LIKE '"
					+ tree_depcode
					+ "%' or depCode='00') AND batchNo='"
					+ text_value + "'";

			final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
					.create(com.base.myproject.client.tools.GreetingService.class);
			greetingService.getDataSet(sql, new AsyncCallback<DataSet>() {
				@Override
				public void onFailure(Throwable caught) {
				}

				@Override
				public void onSuccess(DataSet result) {
					if (result.getRowCount() < 1) {// 返回结果为0
						store.trySave();
					} else {
						return;
					}
				}
			});
		}
	}

}
